package com.xiaoma.chat.service;

import java.util.Date;

import io.rong.ApiHttpClient;
import io.rong.models.FormatType;
import io.rong.models.SdkHttpResult;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.xiaoma.chat.domain.HistoryMessageRecord;
import com.xiaoma.chat.domain.SyncMessageRecord;
import com.xiaoma.chat.resource.IMConstants;
import com.xiaoma.chat.utils.FileUtils;
import com.xiaoma.chat.utils.IMDateUtils;
import com.xiaoma.chat.utils.ZipUtils;

@Service
public class MessageJob {
    
    private static final String tmpPath = "/history/";
    private Logger LOG = LoggerFactory.getLogger(MessageJob.class);
    @Autowired
    private HistoryService historyService;

    @Scheduled(cron="0 0 3 * * ?")
    public void getMessage() {
        try {
            SyncMessageRecord lastRecord = historyService.getLastRecord();
            if (lastRecord != null) {//上次消息记录
                String lastDate = lastRecord.getDate();
                String syncDay = IMDateUtils.getSpecifiedDayAfter(lastDate);
                while (IMDateUtils.isBeforNow(syncDay)) {//有可能中间断了几天，所以需要循环判断，把丢失的信息补回来
                    syncDay(syncDay);
                    syncDay = IMDateUtils.getSpecifiedDayAfter(syncDay);
                }
            } else {//首次同步消息
                String nowStr = IMDateUtils.getFormatedDate(new Date(),"yyyyMMdd");
//                nowStr = "20150725";
                String yesterdayStr = IMDateUtils.getSpecifiedDayBefore(nowStr);
                syncDay(yesterdayStr);
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOG.error(e.getMessage());
        }
    }
    
    private void syncDay(String dayStr) throws Exception {
        for (int i = 0; i < 24; i++) {
            String date = (i < 10) ? dayStr + "0" + i : dayStr + i;
            SdkHttpResult shResult = ApiHttpClient.getMessageHistoryUrl(IMConstants.key, IMConstants.secret, date, FormatType.json);
            if (shResult.getHttpCode() == 200) {
                JSONObject json = JSONObject.fromObject(shResult.getResult());
                String url = json.getString("url");
                if (StringUtils.isNotEmpty(url)) {
                    System.out.println(url);
                    String webRoot = System.getProperty("xmchat.root");
                    FileUtils.download(url, webRoot + tmpPath + date + ".zip");
                    ZipUtils.unzip(webRoot + tmpPath + date + ".zip", webRoot + tmpPath);
                    
                    String[] contents = FileUtils.readContent(webRoot + tmpPath + getFileName(date));
                    for (String line: contents) {
                        int beginIndex = line.indexOf("{");
                        line = line.substring(beginIndex);
                        JSONObject msgJson = JSONObject.fromObject(line);
                        HistoryMessageRecord historyMessageRecord = new HistoryMessageRecord();
                        historyMessageRecord.setAppId(msgJson.getString("appId"));
                        historyMessageRecord.setClassName(msgJson.getString("classname"));
                        historyMessageRecord.setContent(msgJson.getString("content").getBytes());
                        historyMessageRecord.setDateTime(msgJson.getString("dateTime"));
                        historyMessageRecord.setFromUserId(msgJson.getString("fromUserId"));
                        historyMessageRecord.setGroupId(msgJson.getString("GroupId"));
                        historyMessageRecord.setTargetId(msgJson.getString("targetId"));
                        historyMessageRecord.setTargetType(msgJson.getInt("targetType"));
                        historyService.save(historyMessageRecord);
                    }
                    
                    SyncMessageRecord syncMessageRecord = new SyncMessageRecord();
                    syncMessageRecord.setDate(date);
                    syncMessageRecord.setUrl(url);
                    syncMessageRecord.setCreatedAt(new Date());
                    historyService.save(syncMessageRecord);
                }
                
            }
            
        }
    }
    
    private String getFileName(String source) {
        StringBuffer buffer = new StringBuffer();
        return buffer.append(source.substring(0, 4)).append("-").append(source.substring(4, 6)).append("-").append(source.substring(6, 8)).append("-").append(source.substring(8)).toString();
    }
   
    
    public static void main(String[] args) throws Exception {
//        SdkHttpResult shResult = ApiHttpClient.getMessageHistoryUrl(IMConstants.key, IMConstants.secret, "2015072414", FormatType.json);
//        System.out.println(shResult.getHttpCode());
//        JSONObject json = JSONObject.fromObject(shResult.getResult());
//        String url = json.getString("url");
//        System.out.println(url);
//        System.out.println(json.getString("code"));
//        System.out.println(json.getString("date"));
//        FileUtils.download(url, "/Users/houxiufeng/Desktop/2015072414.zip");
        
//        ZipUtils.unzip("/Users/houxiufeng/Desktop/2015072414.zip", "/Users/houxiufeng/Desktop/fitz/");
        
//        String[] ss = FileUtils.readContent("/Users/houxiufeng/Desktop/fitz/2015-07-24-14");
//        for (String s: ss) {
//            int i = s.indexOf("{");
//            s = s.substring(i);
//            JSONObject json = JSONObject.fromObject(s);
//            System.out.println(json.get("appId"));
//            System.out.println(json.get("fromUserId"));
//        }
//        System.out.println(getFileName("2015072414"));
    }
}
